define("func/measureedit", [
    "leaflet",
    "func/base",
    "control/panel",
    "plugins/mcscroll"
], function(L) {

    L.ICT.Func.add("MeasureEdit", {
        Class: L.Class.extend({

            initialize: function() {
                this.ictmap = L.ict.app.ictmap;
                this._popPanel = null;
                this._layergroup = null;
            },

            start: function() {
                this.stop();
                this._initUi();
                this._initEvts();
            },

            stop: function() {
                if (this._popPanel) {
                    this._popPanel.remove();
                }
                if (this.ictmap.map.hasLayer(this._layergroup)) {
                    this.ictmap.map.removeLayer(this._layergroup);
                }
            },

            _initUi: function() {
                var options = {
                    title: '距离量算',
                    width: 360,
                    height: 300
                };
                options.contentHTML = this._container = $(this.getContentHTML());
                var pop = this._popPanel = new L.ICT.PopPanel(options);
                pop.show();
                pop.on("popPanelRemove", function() {
                    this._popPanel = null;
                    this._container = null;
                    this.stop();
                }, this);

            },

            getContentHTML: function() {
                var html = [];
                html.push('<div class="measureeditContainer">');
                html.push('<div class="thDiv"><table><tr><th>经度</th><th>纬度</th></tr></table></div>');
                html.push('<div class="tbDiv">');
                html.push('<table class="tbTable">');
                html.push(this.getItemHtml());
                html.push(this.getItemHtml());
                html.push('</table>');
                html.push('</div>');
                html.push('<div class="btn addBtn"><span class="glyphicon glyphicon-plus"></span></div>');
                // html.push('<p class="msg"></p>');
                html.push('<div class="btnDiv">');
                html.push('<button type="button" class="btn okBtn">确定</button>');
                html.push('<button type="button" class="btn cancelBtn">取消</button>');
                html.push('</div>');
                html.push('</div>');
                return html.join('');
            },

            getItemHtml: function() {
                var itemhtml = [];
                itemhtml.push('<tr>');
                itemhtml.push('<td class="lng lng_d"><input type="text" value="0"></td>');
                itemhtml.push('<td class="dfm">°</td>');
                itemhtml.push('<td class="lng lng_f"><input type="text" value="0"></td>');
                itemhtml.push('<td class="dfm">\′</td>');
                itemhtml.push('<td class="lng lng_m"><input type="text" value="0"></td>');
                itemhtml.push('<td class="dfm">″</td>');
                itemhtml.push('<td class="lngWE lng_W active">W</td>');
                itemhtml.push('<td class="lngWE lng_E">E</td>');
                itemhtml.push('<td class="space">&nbsp&nbsp</td>');
                itemhtml.push('<td class="lat lat_d"><input type="text" value="0"></td>');
                itemhtml.push('<td class="dfm">°</td>');
                itemhtml.push('<td class="lat lat_f"><input type="text" value="0"></td>');
                itemhtml.push('<td class="dfm">\′</td>');
                itemhtml.push('<td class="lat lat_m"><input type="text" value="0"></td>');
                itemhtml.push('<td class="dfm">″</td>');
                itemhtml.push('<td class="latNS lat_N active">N</td>');
                itemhtml.push('<td class="latNS lat_S">S</td>');
                itemhtml.push('<td class="space">&nbsp&nbsp</td>');
                itemhtml.push('<td class="btn deletebtn"><span class="glyphicon glyphicon-remove"></span></td>');
                itemhtml.push('</tr>');
                return itemhtml.join('');
            },

            _initItemEvts: function() {
                this._container.find('.tbTable .lngWE').on('click', function(e) {
                    $(this).addClass('active').siblings('.lngWE').removeClass('active');
                });
                this._container.find('.tbTable .latNS').on('click', function(e) {
                    $(this).addClass('active').siblings('.latNS').removeClass('active');
                });
                this._container.find('.deletebtn').on('click', function(e) {
                    $(this).parent().remove();
                });
            },

            _initEvts: function() {
                var self = this;

                this._container.find('.tbDiv').mCustomScrollbar({ theme: "minimal-dark" });

                this._container.find('.addBtn').on('click', function(e) {
                    self._container.find('.tbTable').append(self.getItemHtml());
                    self._container.find('.tbDiv').mCustomScrollbar("scrollTo", "bottom", {
                        scrollEasing: "easeOut"
                    });
                    self._initItemEvts();
                });

                this._container.find('.okBtn').on('click', this._okEvts.bind(this));

                this._container.find('.cancelBtn').on('click', function(e) {
                    self.stop();
                });

                this._initItemEvts();
            },

            _okEvts: function(e) {
                if (this.ictmap.map.hasLayer(this._layergroup)) {
                    this.ictmap.map.removeLayer(this._layergroup);
                }
                var latlngs = this.getLatLngs();
                if (!L.ict.app.util.tool.checkLatLngs(latlngs)){
                  L.ict.app.util.dialog.error('错误', '经纬度范围不合法！');
                  return;
                }
                if (latlngs.length < 2) {
                    L.ict.app.util.dialog.error('错误', '请至少输入两个点才能测量距离！');
                    return;
                }
                this._layergroup = L.featureGroup().addTo(this.ictmap.map);
                this.createPolyline(latlngs);
                this.createPoints(latlngs);
                this.createInfos(latlngs);
            },

            createPoints: function(latlngs) {
                var icon = new L.DivIcon({ //顶点样式
                    iconSize: new L.Point(8, 8),
                    className: 'ict_measure_vetixicon'
                });
                for (var i = 0, len = latlngs.length; i < len; i++) {
                    var latlng = latlngs[i];
                    var lat = L.ict.app.util.tool.latlngTodfmStr(latlng.lat, 'lat');
                    var lon = L.ict.app.util.tool.latlngTodfmStr(latlng.lng, 'lng');
                    var title = '经度：' + lon + '，' + '纬度：' + lat;

                    var marker = new L.Marker(latlng, {
                        icon: icon,
                        title: title
                    });
                    this._layergroup.addLayer(marker);
                }
            },

            createPolyline: function(latlngs) {
                var shapeOptions = {
                    stroke: true,
                    color: '#116cc1',
                    weight: 2,
                    opacity: 1,
                    fill: false,
                    clickable: true
                };
                var ply = L.polyline(latlngs, shapeOptions);
                this._layergroup.addLayer(ply);
                this.ictmap.map.fitBounds(ply.getBounds());
            },

            createInfos: function(latlngs) {
                var len = latlngs.length,
                    sum = 0;
                for (var i = 1; i < len; i++) {
                    sum += this.caculatDistance(latlngs[i - 1], latlngs[i]);
                    this.createInfoICon(latlngs[i], sum.toFixed(2));
                    if (i === len - 1) {
                        this.createCloseICon(latlngs[i]);
                    }
                }
            },

            createInfoICon: function(latlng, value) {
                var divIcon = L.divIcon({
                    iconSize: [100, 20],
                    iconAnchor: [-2, -2],
                    className: 'ict_measure_infoIcon',
                    html: value + '海里'
                });
                var infomarker = L.marker(latlng, { icon: divIcon });
                this._layergroup.addLayer(infomarker);
            },

            createCloseICon: function(latlng) {
                var closeIcon = L.icon({
                    iconUrl: 'themes/images/shipIcons/hjxs_close.png', //icon图标的左上角对准latlng点
                    iconSize: [18, 18],
                    iconAnchor: [-9, 14], //程序解析后变成margin-left:9px;margin-top:-14px;
                    className: 'ict_measure_closeicon'
                });
                var closemarker = L.marker(latlng, { icon: closeIcon });
                this._layergroup.addLayer(closemarker);
                closemarker.on("click", function() {
                    this.ictmap.map.removeLayer(this._layergroup);
                }, this);
            },

            caculatDistance: function(latlng1, latlng2) {
                var meter = latlng1.distanceTo(latlng2);
                return +L.ict.app.util.tool.convertMileToNmile(meter);
            },

            getLatLngs: function() {
                var latlngs = [];
                var ts = this._container.find(".tbTable tr");
                for (var i = 0, len = ts.length; i < len; i++) {
                    var $tr = $(ts[i]);
                    var lad = $tr.find('.lat_d input').val(),
                        laf = $tr.find('.lat_f input').val(),
                        lam = $tr.find('.lat_m input').val(),
                        ns = $tr.find('.latNS.active').text(),
                        lgd = $tr.find('.lng_d input').val(),
                        lgf = $tr.find('.lng_f input').val(),
                        lgm = $tr.find('.lng_m input').val();
                    we = $tr.find('.lngWE.active').text()
                    var lat = Math.abs(parseFloat(lad)) + parseFloat(laf / 60) + parseFloat(lam / 3600),
                        lng = Math.abs(parseFloat(lgd)) + parseFloat(lgf / 60) + parseFloat(lgm / 3600);
                    lat = ns == "S" ? -lat : lat;
                    lng = we == "W" ? -lng : lng;
                    var latlng = L.latLng([lat, lng]);
                    latlngs.push(latlng);
                }
                return latlngs;
            }
        })
    });
});
